package com.xdemo.personal.communityclient;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;

import com.xdemo.core.msg.RegisterServerMessage;
import com.xdemo.personal.config.PersonalServerConfig;
import com.xdemo.processor.IProcessor;
import com.xdemo.server.BaseServerMessage;
import com.xdemo.server.ServerSource;

public class CommunityClientHandler extends SimpleChannelUpstreamHandler {

	private IProcessor<Integer> processor;
	
	public CommunityClientHandler(IProcessor<Integer> processor) {
		this.processor = processor;
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e)
			throws Exception {
		RegisterServerMessage _msg = new RegisterServerMessage();
		_msg.setServerId(PersonalServerConfig.getInstance().getServerId());
		ctx.getChannel().write(_msg);
	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {
		if(!(e.getMessage() instanceof BaseServerMessage)) {
			return;
		}
		BaseServerMessage _message = (BaseServerMessage)e.getMessage();
		ServerSource _server = (ServerSource)ctx.getAttachment();
		if(_server == null) {
			_server = new ServerSource();
			_server.setContext(ctx);
			ctx.setAttachment(_server);
		}
		_message.setServer(_server);
		processor.execute(_message);
	}
	
}
